package com.golddaymicromall.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import org.apache.http.HttpStatus;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

/**
 * Miscellaneous agent utility methods.
 */
public class AgentUtils {

	/** Package Info */
	private static PackageInfo packageInfo = null;

	public static final String TAG = "AgentUtils";

	public static final String PREFERENCE_NEWS = "news";

	public static final String PREFERENCE_FONT_SIZE = "fontSize";

	public static final String PREFERENCE_IF_INPUT = "input";

	/** Get Package Info */
	public static PackageInfo getPackageInfo(Context context) {
		if (packageInfo == null) {
			try {
				packageInfo = context.getPackageManager().getPackageInfo(
						context.getPackageName(), 0);
			} catch (NameNotFoundException e) {
				packageInfo = new PackageInfo();
			}
		}
		return packageInfo;
	}

	/** Decode a bitmap */
	public static Bitmap decodeBitmap(String path, double needSize) {
		Bitmap bitmap = null;
		// Decode image size
		BitmapFactory.Options bfo = new BitmapFactory.Options();
		bfo.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, bfo);
		// Calculate scale
		int scale = (int) Math.round(Math.sqrt(bfo.outHeight * bfo.outWidth)
				/ needSize);
		if (scale < 1) {
			scale = 1;
		}
		// Decode with inSampleSize
		BitmapFactory.Options resize = new BitmapFactory.Options();
		resize.inSampleSize = scale;
//		Log.e("inSampleSize", scale + "");
		bitmap = BitmapFactory.decodeFile(path, resize);
		return bitmap;
	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		return (networkInfo != null && networkInfo.isAvailable());
		// return true;
	}

	public static File getFileFromBytes(byte[] btyes, String outputFile) {
		File file = null;
		BufferedOutputStream stream = null;
		FileOutputStream fstream = null;
		try {
			file = new File(outputFile);
			fstream = new FileOutputStream(file);

			stream = new BufferedOutputStream(fstream);
			stream.write(btyes);
			stream.close();
			fstream.close();
		} catch (FileNotFoundException e) {
//			Log.e("AgentUtils", "getFileFromBytes", e);
		} catch (IOException e) {
//			Log.e("AgentUtils", "getFileFromBytes", e);
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
//					Log.e("AgentUtils", "getFileFromBytes", e);
				}
			}
			if (fstream != null) {
				try {
					fstream.close();
				} catch (IOException e) {
//					Log.e("AgentUtils", "getFileFromBytes", e);
				}
			}
		}
		return file;
	}

	/**
	 * sp转为px
	 */
	public static int sp2px(Context context, float spValue) {
		float fontScale = context.getResources().getDisplayMetrics().density;
		return (int) (spValue * fontScale + 0.5f);
	}

	/**
	 * dip转为PX
	 */
	public static int dip2px(Context context, float dipValue) {
		float fontScale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * fontScale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 图片转字节数组
	 * 
	 * @param bitmap
	 * @return
	 */
	public static byte[] getBytesFromBitmap(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, baos);
		byte[] bytes = baos.toByteArray();
		return bytes;
	}

	public static Bitmap getBitmapFromByte(byte[] param) {
		if (param != null && param.length > 0) {
			return BitmapFactory.decodeByteArray(param, 0, param.length);
		}
		return null;
	}

	/**
	 *
	 * @param bitmap
	 * @return
	 */
	public static byte[] bitmapToBytes(Bitmap bitmap) {
		if (bitmap == null) {
			return null;
		}
		byte[] result = null;
		ByteArrayOutputStream os = null;
		try {
			os = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 100, os);
			result = os.toByteArray();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
//					Log.e("AgentUtils", "bitmapToBytes", e);
				}
			}
		}
		return result;
	}

	/**
	 *
	 * @param view
	 */
	public static void getFocus(View view) {
		view.setFocusable(true);
		view.setFocusableInTouchMode(true);
		view.requestFocus();
		view.requestFocusFromTouch();
	}

	/**
	 * 打开图片
	 * 
	 * @param param
	 * @return
	 */
	public static Intent getImageFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	public static int getScreenWidth(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		return dm.widthPixels;
	}

	public static int getScreenHeight(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		return dm.heightPixels;
	}

	/**
	 *
	 */
	public static Bitmap stringToBitmap(String string) {
		byte[] bytes = Base64.decode(string, Base64.DEFAULT);
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}

	public static Bitmap zoomImg(Bitmap bm, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleWidth);
		Bitmap result = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);
		return result;
	}

	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = null;
		ByteArrayInputStream isBm = null;
		Bitmap bitmap = null;
		try {
			baos = new ByteArrayOutputStream();
			image.compress(CompressFormat.JPEG, 100, baos);
			int options = 100;
			while (baos.toByteArray().length / 1024 > 100) {
				baos.reset();
				image.compress(CompressFormat.JPEG, options, baos);
				options -= 10;
			}
			isBm = new ByteArrayInputStream(baos.toByteArray());
			bitmap = BitmapFactory.decodeStream(isBm, null, null);
			baos.close();
			isBm.close();
		} catch (IOException e) {
//			Log.e("AgentUtils", "compressImage", e);
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
//					Log.e("AgentUtils", "compressImage", e);
				}
			}
			if (isBm != null) {
				try {
					isBm.close();
				} catch (IOException e) {
//					Log.e("AgentUtils", "compressImage", e);
				}
			}
		}
		return bitmap;
	}

//	public static Bitmap getBitmapFromURL(String path) throws IOException {
//		URL url = new URL(path);
//		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//		conn.setConnectTimeout(5000);
//		conn.setRequestMethod("GET");
//		if (conn.getResponseCode() == HttpStatus.SC_OK) {
//			InputStream inStream = conn.getInputStream();
//			Bitmap bitmap = BitmapFactory.decodeStream(inStream);
//			return bitmap;
//		}
//		return null;
//	}

	/**
	 * 括弧の使用チェック
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkBracket(String str) {
		if (str == null || str.length() == 0) {
			return true;
		} else {
			return Pattern.matches("[^〔〕()<>《》\\[\\]{}（）【】［］｛｝〈〉「」『』＜＞??]+",
					str);
		}
	}

	/**
	 * 获取状态栏高度
	 * 
	 * @param activity
	 * @return > 0 success; <= 0 fail
	 */
	public static int getStatusHeight(Activity activity) {
		int statusHeight = 0;
		Rect localRect = new Rect();
		activity.getWindow().getDecorView()
				.getWindowVisibleDisplayFrame(localRect);
		statusHeight = localRect.top;
		if (0 == statusHeight) {
			Class<?> localClass;
			try {
				localClass = Class.forName("com.android.internal.R$dimen");
				Object localObject = localClass.newInstance();
				int i5 = Integer.parseInt(localClass
						.getField("status_bar_height").get(localObject)
						.toString());
				statusHeight = activity.getResources()
						.getDimensionPixelSize(i5);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		return statusHeight;
	}

	/**
	 * 共通方法：拍照
	 * 
	 */
	public static void takePhotos(Context context, File currentFile,
			int requestCode) {
		Uri uri = null;
		// 启动照相机
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		try {
			// 在SD卡创建一个新的文件
			uri = Uri.fromFile(currentFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 设置输出路径到新建的文件
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		// 拍照回调
		((Activity) context).startActivityForResult(intent, requestCode);
	}

	/**
	 * 获取Bitmap实际大小
	 * 
	 * @param originalBmp
	 */
	public static void getBitmapSize(Bitmap originalBmp, String path) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		originalBmp.compress(CompressFormat.JPEG, 100, os);
		byte[] bytes = os.toByteArray();
		File mPhotoFile = AgentUtils.getFileFromBytes(bytes, path);
		FileInputStream fs;
		try {
			fs = new FileInputStream(mPhotoFile);
			int length;
			try {
				length = fs.available();
//				Log.e("New File：", path + "   " + length / 1024 + "K");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 把单个英文字母或者字符串转换成数字ASCII码
	 * 
	 * @param input
	 * @return
	 */
	public static int character2ASCII(String input) {
		char[] temp = input.toCharArray();
		StringBuilder builder = new StringBuilder();
		for (char each : temp) {
			builder.append((int) each);
		}
		String result = builder.toString();
		return Integer.parseInt(result);
	}

	/**
	 * 文件转bitmap
	 * 
	 * @param bitmapPath
	 * @return
	 */
	public static Bitmap decodeBitmap(String bitmapPath) {
		return BitmapFactory.decodeFile(bitmapPath);
	}

	/**
	 * 格林尼治转本地
	 * 
	 * @param gmt
	 * @return
	 */
	public static String convertGMTToLoacale(String gmt) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		return sdf.format(date);
		// String cc = gmt.substring(0, 19) + gmt.substring(33, 38);
		// SimpleDateFormat sdf = new
		// SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy",
		// Locale.ENGLISH);
		// try {
		// Date date = sdf.parse(cc);
		// SimpleDateFormat dateformat = new SimpleDateFormat(
		// "yyyy-MM-dd HH:mm:ss");
		// String result = dateformat.format(date);
		// return result;
		// } catch (ParseException e) {
		// }
		// return "";
	}

	/**
	 * 获取外置SD卡路径
	 * 
	 * @return
	 */
	public static String getSDCardPath() {
		return Environment.getExternalStorageDirectory().toString();
	}

	/**
	 * 获取内置空间路径
	 * 
	 * @return
	 */
	@SuppressLint("SdCardPath")
	public static String getDeviceCardPath() {
		return Environment.getExternalStorageDirectory().getParent().toString()
				+ "/sdcard1";
	}

	public static Bitmap reSizeBitmap(String filePath, int maxLength) {
		Bitmap bm = getSmallBitmap(filePath, maxLength);
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			bm.compress(CompressFormat.JPEG, 80, baos);
			baos.close();
		} catch (IOException e) {
//			Log.e("ImageUtil", "reSizeBitmap", e);
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
//					Log.e("ImageUtil", "reSizeBitmap", e);
				}
			}
		}
		return bm;
	}

	public static Bitmap getSmallBitmap(String filePath, int maxLength) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		int width = options.outWidth;
		int height = options.outHeight;
		int reqWidth = 0;
		int reqHeight = 0;
		float scal = height / (float) width;
		float scal2 = width / (float) height;
		if (scal > scal2) {
			if (height > maxLength) {
				reqHeight = maxLength;
				reqWidth = (int) (reqHeight / scal);
			} else {
				reqHeight = height;
				reqWidth = width;
			}
		} else {
			if (width > maxLength) {
				reqWidth = maxLength;
				reqHeight = (int) (reqWidth / scal2);
			} else {
				reqWidth = width;
				reqHeight = height;
			}
		}
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 获取等比例压缩后的图片
	 * 
	 * @param filePath
	 * @return
	 */
	public static Bitmap getResizedBitmap(String filePath, int maxLength) {
		// 获取原始图片的宽高
		BitmapFactory.Options options = new BitmapFactory.Options();
		// 不读入内存
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		int height = options.outHeight;
		int width = options.outWidth;
		// 根据最长边的大小计算实际输出大小
		int reqWidth = 0;
		int reqHeight = 0;
		float scal = height / (float) width;
		float scal2 = width / (float) height;
		if (scal > scal2) {
			if (height > maxLength) {
				reqHeight = maxLength;
				reqWidth = (int) (reqHeight / scal);
			} else {
				reqHeight = height;
				reqWidth = width;
			}
		} else {
			if (width > maxLength) {
				reqWidth = maxLength;
				reqHeight = (int) (reqWidth / scal2);
			} else {
				reqWidth = width;
				reqHeight = height;
			}
		}
		// 压缩比例
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		// 在内存中创建Bitmap
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 计算压缩比例
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	/**
	 * 生成上传的文件
	 * 
	 * @param bitmap
	 * @param filePath
	 * @param rate
	 *            压缩比例
	 * @return
	 */
	public static File getUploadBitmapFile(Bitmap bitmap, String filePath,
			int rate) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, rate, os);
		byte[] bytes = os.toByteArray();
		File mPhotoFile = AgentUtils.getFileFromBytes(bytes, filePath);
		FileInputStream fs;
		try {
			fs = new FileInputStream(mPhotoFile);
			int length;
			try {
				length = fs.available();
//				Log.e("New File：", filePath + "   " + length / 1024 + "K");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return mPhotoFile;
	}

	/**
	 * MD5加密
	 * 
	 * @param s
	 * @return String
	 */
	public static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str).toUpperCase();
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 半角转全角
	 * 
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375) {
				c[i] = (char) (c[i] - 65248);
			}
		}
		return new String(c);
	}

	/**
	 * 用来判断服务是否运行.
	 * 
	 * @param className
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(1000);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	/**
	 * 用来判断服务是否运行.
	 * 
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public static boolean isAppRunning(Context mContext, String packageName) {
		boolean isRunning = false;
		ActivityManager am = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(100);
		for (RunningTaskInfo info : list) {
			if (info.topActivity.getPackageName().equals(packageName)
					|| info.baseActivity.getPackageName().equals(packageName)) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	/**
	 * 设置子控件TextView不可用
	 * 
	 * @param dp
	 */
	public static void setDisabledEditTexts(ViewGroup dp) {
		for (int x = 0, n = dp.getChildCount(); x < n; x++) {
			View v = dp.getChildAt(x);
			if (v instanceof EditText) {
				v.setFocusable(false);
				v.setClickable(false);
				v.setFocusableInTouchMode(false);
				v.setLongClickable(false);
			} else if (v instanceof ViewGroup) {
				setDisabledEditTexts((ViewGroup) v);
			}
		}
	}

	/**
	 * 产生随机字符串
	 * */
	public static final String randomString(int length) {
		Random randGen = null;
		char[] numbersAndLetters = null;
		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			randGen = new Random();
			numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
					+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}

	public static boolean isLogin() {
		return true;
	}

	/**
	 * 获取通知栏高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusBarHeight(Context context) {
		Class c = null;
		Object bj = null;
		Field field = null;
		int x = 0, statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			bj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(bj).toString());
			statusBarHeight = context.getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}

	/**
	 * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
	 * 
	 * @param context
	 * @return true 表示开启
	 */
	public static final boolean isGPSOpen(final Context context) {
		LocationManager locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	/**
	 * 跳转到网络设置画面
	 * 
	 * @param activity
	 */
	public static void gotoGpsSystemSetting(Activity activity) {
		Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		activity.startActivityForResult(intent, 8888);
	}

	/**
	 * 强制帮用户打开GPS
	 * 
	 * @param context
	 */
	public static final void openGPS(Context context) {
		Intent GPSIntent = new Intent();
		GPSIntent.setClassName("com.android.settings",
				"com.android.settings.widget.SettingsAppWidgetProvider");
		GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
		GPSIntent.setData(Uri.parse("custom:3"));
		try {
			PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
		} catch (CanceledException e) {
			e.printStackTrace();
		}
	}

	public static boolean isBlank(String string) {
		if (null == string || "".equals(string.trim())) {
			return true;
		}
		return false;
	}

	public static List<String> getProviders(Context context) {
		LocationManager lm = ((LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE));
		return lm.getProviders(true);
	}

	/**
	 * 返回byte的数据大小对应的文本
	 * 
	 * @param size
	 * @return
	 */
	public static String formatFileSize(long size) {
		DecimalFormat formater = new DecimalFormat("####.00");
		if (size < 1024) {
			return size + "bytes";
		} else if (size < 1024 * 1024) {
			float kbsize = size / 1024f;
			return formater.format(kbsize) + "KB";
		} else if (size < 1024 * 1024 * 1024) {
			float mbsize = size / 1024f / 1024f;
			return formater.format(mbsize) + "MB";
		} else if (size < 1024 * 1024 * 1024 * 1024) {
			float gbsize = size / 1024f / 1024f / 1024f;
			return formater.format(gbsize) + "GB";
		} else {
			return "size: error";
		}
	}

	/**
	 * 手机号验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}

	/**
	 * 电话号码验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isPhone(String str) {
		Pattern p1 = null, p2 = null;
		Matcher m = null;
		boolean b = false;
		p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
		p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
		if (str.length() > 9) {
			m = p1.matcher(str);
			b = m.matches();
		} else {
			m = p2.matcher(str);
			b = m.matches();
		}
		return b;
	}

	public static boolean isContainsNumberAndLetter(String str) {
		boolean isDigit = false;// 定义一个boolean值，用来表示是否包含数字
		boolean isLetter = false;// 定义一个boolean值，用来表示是否包含字母
		for (int i = 0; i < str.length(); i++) { // 循环遍历字符串
			if (Character.isDigit(str.charAt(i))) { // 用char包装类中的判断数字的方法判断每一个字符
				isDigit = true;
			}
			if (Character.isLetter(str.charAt(i))) { // 用char包装类中的判断字母的方法判断每一个字符
				isLetter = true;
			}
		}
		return isDigit && isLetter;
	}

	// 金额验证
	public static boolean isNumber(String str) {
		Pattern pattern = Pattern
				.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
		Matcher match = pattern.matcher(str);
		if (match.matches() == false) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 获取APP版本名称
	 * @return
	 */
	public static String getVersionName(Context context) {
		String name = "";
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
			name = info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return name;
	}
}
